package com.ruoyi.business.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.ruoyi.business.VO.MonthVO;
import com.ruoyi.business.VO.RankVO;
import com.ruoyi.business.VO.StatisticsVO;
import com.ruoyi.business.domain.BuCustom;
import com.ruoyi.business.domain.BuEarningsRecords;
import com.ruoyi.business.domain.BuSharing;
import com.ruoyi.business.service.IBuCustomService;
import com.ruoyi.business.service.IBuEarningsRecordsService;
import com.ruoyi.business.service.IBuSharingService;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.BuEarningsMapper;
import com.ruoyi.business.domain.BuEarnings;
import com.ruoyi.business.service.IBuEarningsService;

import static com.ruoyi.common.utils.SecurityUtils.getUserId;

/**
 * 收益Service业务层处理
 *
 * @author ruoyi
 * @date 2024-09-12
 */
@Service
public class BuEarningsServiceImpl implements IBuEarningsService
{
    @Autowired
    private BuEarningsMapper buEarningsMapper;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IBuEarningsRecordsService buEarningsRecordsService;
    @Autowired
    private IBuCustomService buCustomService;
    @Autowired
    private IBuSharingService buSharingService;
    /**
     * 查询收益
     *
     * @param id 收益主键
     * @return 收益
     */
    @Override
    public BuEarnings selectBuEarningsById(Long id)
    {
        return buEarningsMapper.selectBuEarningsById(id);
    }

    /**
     * 查询收益列表
     *
     * @param buEarnings 收益
     * @return 收益
     */
    @Override
    public List<BuEarnings> selectBuEarningsList(BuEarnings buEarnings)
    {
        return buEarningsMapper.selectBuEarningsList(buEarnings);
    }

    /**
     * 新增收益
     *
     * @param buEarnings 收益
     * @return 结果
     */
    @Override
    public int insertBuEarnings(BuEarnings buEarnings)
    {
        buEarnings.setCreatedAt( new Date() );
        buEarnings.setCreatedBy( getUserId() );
        //计算碳排放量
        BigDecimal conserveElectricity = new BigDecimal(buEarnings.getConserveElectricity().toString());
        BigDecimal factor = new BigDecimal("0.785");
        buEarnings.setCarbonEmissions( conserveElectricity.multiply(factor).setScale(3, RoundingMode.HALF_UP) );
        buEarningsMapper.insertBuEarnings(buEarnings);

        //总分润
        BigDecimal total = BigDecimal.ZERO;

        //查出客户信息
        BuCustom buCustom = buCustomService.selectBuCustomByCustomId(buEarnings.getCustomId());
        BigDecimal customAllocationDecimal = new BigDecimal(buCustom.getCustomAllocation().toString());
        // 除以 100
        BigDecimal result = customAllocationDecimal.divide(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
        BigDecimal customAmount = buEarnings.getEarningsAmount().multiply(result).setScale(2, RoundingMode.HALF_UP);
        total = total.add(customAmount);
        BuEarningsRecords buEarningsRecords = new BuEarningsRecords();
        buEarningsRecords.setEarningsId(buEarnings.getId());
        buEarningsRecords.setUserId(buCustom.getUserId());
        buEarningsRecords.setEarningsAmount(customAmount);
        buEarningsRecords.setTime( new Date() );
        buEarningsRecordsService.insertBuEarningsRecords(buEarningsRecords);

        //查出分润占比
        BuSharing buSharing = new BuSharing();
        buSharing.setCustomId(buCustom.getCustomId());
        List<BuSharing> list = buSharingService.selectBuSharingList(buSharing);
        for (BuSharing buSharing1 : list){
            BigDecimal customAllocationDecimal2 = new BigDecimal(buSharing1.getProfitSharing().toString());
            BigDecimal baifenbi = customAllocationDecimal2.divide(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
            BigDecimal customAmount2 = buEarnings.getEarningsAmount().multiply(baifenbi).setScale(2, RoundingMode.HALF_UP);
            total = total.add(customAmount2);
            BuEarningsRecords buEarningsRecords2 = new BuEarningsRecords();
            buEarningsRecords2.setEarningsId(buEarnings.getId());
            buEarningsRecords2.setUserId(buSharing1.getUserId());
            buEarningsRecords2.setEarningsAmount(customAmount2);
            buEarningsRecords2.setTime( new Date() );
            buEarningsRecordsService.insertBuEarningsRecords(buEarningsRecords2);
        }

        //计算公司分润
        buEarnings.setFirmAmount(buEarnings.getEarningsAmount().subtract(total));

        //更新账户
        return buEarningsMapper.updateBuEarnings(buEarnings);
    }

    /**
     * 修改收益
     *
     * @param buEarnings 收益
     * @return 结果
     */
    @Override
    public int updateBuEarnings(BuEarnings buEarnings)
    {
        BuEarningsRecords buEarningsRecords3 = new BuEarningsRecords();
        buEarningsRecords3.setEarningsId(buEarnings.getId());
        List<BuEarningsRecords> buEarningsRecordsList = buEarningsRecordsService.selectBuEarningsRecordsList(buEarningsRecords3);
        for (BuEarningsRecords buEarningsRecords1 : buEarningsRecordsList){
            buEarningsRecordsService.deleteBuEarningsRecordsById(buEarningsRecords1.getId());
        }
        //计算碳排放量
        BigDecimal conserveElectricity = new BigDecimal(buEarnings.getConserveElectricity().toString());
        BigDecimal factor = new BigDecimal("0.785");
        buEarnings.setCarbonEmissions( conserveElectricity.multiply(factor).setScale(3, RoundingMode.HALF_UP) );
        buEarningsMapper.updateBuEarnings(buEarnings);

        //总分润
        BigDecimal total = BigDecimal.ZERO;

        //查出客户信息
        BuCustom buCustom = buCustomService.selectBuCustomByCustomId(buEarnings.getCustomId());
        BigDecimal customAllocationDecimal = new BigDecimal(buCustom.getCustomAllocation().toString());
        // 除以 100
        BigDecimal result = customAllocationDecimal.divide(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
        BigDecimal customAmount = buEarnings.getEarningsAmount().multiply(result).setScale(2, RoundingMode.HALF_UP);
        total = total.add(customAmount);
        BuEarningsRecords buEarningsRecords = new BuEarningsRecords();
        buEarningsRecords.setEarningsId(buEarnings.getId());
        buEarningsRecords.setUserId(buCustom.getUserId());
        buEarningsRecords.setEarningsAmount(customAmount);
        buEarningsRecords.setTime( new Date() );
        buEarningsRecordsService.insertBuEarningsRecords(buEarningsRecords);

        //查出分润占比
        BuSharing buSharing = new BuSharing();
        buSharing.setCustomId(buCustom.getCustomId());
        List<BuSharing> list = buSharingService.selectBuSharingList(buSharing);
        for (BuSharing buSharing1 : list){
            BigDecimal customAllocationDecimal2 = new BigDecimal(buSharing1.getProfitSharing().toString());
            BigDecimal baifenbi = customAllocationDecimal2.divide(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
            BigDecimal customAmount2 = buEarnings.getEarningsAmount().multiply(baifenbi).setScale(2, RoundingMode.HALF_UP);
            total = total.add(customAmount2);
            BuEarningsRecords buEarningsRecords2 = new BuEarningsRecords();
            buEarningsRecords2.setEarningsId(buEarnings.getId());
            buEarningsRecords2.setUserId(buSharing1.getUserId());
            buEarningsRecords2.setEarningsAmount(customAmount2);
            buEarningsRecords2.setTime( new Date() );
            buEarningsRecordsService.insertBuEarningsRecords(buEarningsRecords2);
        }

        //计算公司分润
        buEarnings.setFirmAmount(buEarnings.getEarningsAmount().subtract(total));

        //更新账户
        return buEarningsMapper.updateBuEarnings(buEarnings);
    }

    /**
     * 批量删除收益
     *
     * @param ids 需要删除的收益主键
     * @return 结果
     */
    @Override
    public int deleteBuEarningsByIds(Long[] ids)
    {
        // 删除收益记录
        for (Long id : ids){
            BuEarningsRecords buEarningsRecords = new BuEarningsRecords();
            buEarningsRecords.setEarningsId(id);
            List<BuEarningsRecords> list = buEarningsRecordsService.selectBuEarningsRecordsList(buEarningsRecords);
            for (BuEarningsRecords buEarningsRecords1 : list){
                buEarningsRecordsService.deleteBuEarningsRecordsById(buEarningsRecords1.getId());
            }
        }
        return buEarningsMapper.deleteBuEarningsByIds(ids);
    }

    /**
     * 删除收益信息
     *
     * @param id 收益主键
     * @return 结果
     */
    @Override
    public int deleteBuEarningsById(Long id)
    {
        return buEarningsMapper.deleteBuEarningsById(id);
    }

    private List<SysUser> getSysUserList(Long id){
        SysUser user = new SysUser();
        user.setDeptId(id);
        return userService.selectUserList(user);
    }

    @Override
    public StatisticsVO selectSum()
    {
        return buEarningsMapper.selectSum();
    }

    @Override
    public List<MonthVO> month(){
        List<MonthVO> monthVOList = new ArrayList<>();
        List<Date> lastSixMonths = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();

        for (int i = 0; i < 6; i++) {
            lastSixMonths.add(calendar.getTime());
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
        }

        // 创建DateTimeFormatter对象，指定日期格式为"yyyy-MM"
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM");
        for (Date date : lastSixMonths) {
            // 将Date转换为LocalDate
            LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            // 将LocalDate对象转换为字符串
            String dateString = localDate.format(formatter)+"月";
            MonthVO monthVO = new MonthVO();
            monthVO.setMonth(dateString);
            BigDecimal earningsAmount = buEarningsMapper.month(date);
            if (earningsAmount == null){
                earningsAmount = BigDecimal.ZERO;
            }else {
                earningsAmount=earningsAmount.divide( BigDecimal.valueOf( 10000 ), 2, RoundingMode.HALF_UP);
            }
            monthVO.setEarningsAmount( earningsAmount );
            monthVOList.add( monthVO );
        }
        return monthVOList;
    }

    @Override
    public List<RankVO> rank(String type){
        if ("1".equals( type )) {
            // 获取当月
            Date month = new Date();
            List<RankVO> monthVOList = buEarningsMapper.rank( month );
            return monthVOList;
        }else {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date()); // 获取当前日期
            calendar.add(Calendar.MONTH, -1); // 减去一个月
            Date lastMonth = calendar.getTime();
            List<RankVO> monthVOList = buEarningsMapper.rank( lastMonth );
            return monthVOList;
        }
    }
}
